'use strict';

var debug = require('debug'),
  log = debug('yozh:mw:log'),
  error = debug('yozh:mw:error'),
  verbose = debug('yozh:mw:verbose'),
  uuid = require('uuid'),
  tools = require('../lib/tools'),
  config = require('../config/config'),
  respData = require('../config/json_resp_data');

/**
 * token middleware
 * @param  {Object} opts options
 * @return {Function} ES6 generator function
 */
module.exports = function(opts) {
  var middleware = function *token(next) {
    if (config.skipPath.indexOf(this.path) > -1) {
      log('skip token middleware, path: ' + this.request.method + this.path);
      return yield next;
    }
    // if (this.state.skipChectToken) {
    //   log('skip token middleware.');
    //   return yield next;
    // }
    // this.state.authorization = tools.getToken(this.header);

    var links = respData.createSimpleLinks(this.path);

    var errorId = uuid.v4();
    var errors = respData.createErrors(
      errorId,
      401,
      '01001',
      '',
      '',
      {
        method: this.request.method,
        clentIp: this.ip,
        path: this.path,
        querystring: this.query
      }
    );

    if (this.state.authorization || tools.getToken(this.header)) {
      // set token
      if (this.state.authorization) {
        this.state.authorization = tools.getToken(this.header);
      }
      var res = yield opts.cache.exists(this.state.authorization);
      if (res === 1) {
        // is login;
        yield next;
      } else {
        // this.body = 'Authorization expired';
        errors.detail = '授权超时';
        errors.source = 'Authorization Expired';
        this.body = JSON.stringify({links: links, errors: errors});
        return this.status = 401;
      }
    } else {
      // this.throw(401, 'Authorization Error\n');
      // this.body = 'Authorization Error';
      errors.detail = '授权错误';
      errors.source = 'Authorization Error';
      this.body = JSON.stringify({links: links, errors: errors});

      return this.status = 401;
    }
  };
  return middleware;
};
